package com.shujia.thread;

import java.util.LinkedList;

public class Demo3 {


    public static void main(String[] args) {
        //队列
        LinkedList<Thread> threads = new LinkedList<>();
        Demo4 demo4 = new Demo4(threads);
        for (int i = 0; i < 10; i++) {
            MyThread1 myThread1 = new MyThread1(demo4);
            threads.add(myThread1);
        }
        for (Thread thread : threads) {
            thread.start();
        }

    }


}

class MyThread1 extends Thread {

    private Demo4 demo4;

    public MyThread1(Demo4 demo4) {
        this.demo4 = demo4;
    }

    @Override
    public void run() {
        while (true) {
            Boolean a = demo4.a();
            if (a) {
                break;
            }
        }
    }
}


class Demo4 {
    LinkedList<Thread> threads;
    Integer num = 100;

    public Demo4(LinkedList<Thread> threads) {
        this.threads = threads;
    }

    public synchronized Boolean a() {
        if (num != 0) {
            System.out.println(threads.size());
            num = num - 1;
            System.out.println(Thread.currentThread().getName() + "\t" + num);

            Thread thread = threads.pollFirst();
            if (thread != null) {
                this.notify();
            }

            Thread currentThread = Thread.currentThread();
            threads.addLast(currentThread);
            try {
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return true;
        }
        return false;
    }


}

